package org.example.project3.Service;

import com.fasterxml.jackson.databind.ser.Serializers;
import lombok.extern.slf4j.Slf4j;
import org.example.project3.Context.BaseContext;
import org.example.project3.DTO.RegisterDTO;
import org.example.project3.DTO.UserupdateDTO;
import org.example.project3.Entity.User;
import org.example.project3.Exception.AcountNotExistsException;
import org.example.project3.Exception.LoginFailedException;
import org.example.project3.Exception.PasswordNotExistsException;
import org.example.project3.Mapper.UserMapper;
import org.example.project3.VO.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.LinkOption;
import java.time.LocalDateTime;

@Service
@Slf4j
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    public Integer add(RegisterDTO dto){
        User fresh_user = new User();
        BeanUtils.copyProperties(dto,fresh_user);
        fresh_user.setCreateTime(LocalDateTime.now());
        fresh_user.setUpdateTime(LocalDateTime.now());
        userMapper.add(fresh_user);
        return fresh_user.getId();
    }

    public User login(RegisterDTO dto) throws Exception{
        //1.参数校验，若用户名或密码为空应该抛出异常
        if(dto.getUsername() == null)throw new AcountNotExistsException("用户名为空!");
        else if(dto.getPassword() == null)throw new PasswordNotExistsException("密码为空!");

        //2.查数据库，返回结果
        User user = userMapper.search(dto);
        if( user == null ){
            //抛出用户名或密码不正确异常
            throw new LoginFailedException("用户名或密码不正确!");
        }
        return user;

    }

    public UserVO getUserstatistics(){
        //根据线程变量获取用户id，查询相关信息
        Long id = BaseContext.getCurrentId();
        log.info("当前用户id是：{}",id);
        User user = userMapper.getUserstatistics(Integer.parseInt(String.valueOf(id)));
        UserVO VO = new UserVO();
        BeanUtils.copyProperties(user,VO);
        return VO;
    }

    @Transactional
    public void update(UserupdateDTO dto){
        //封装user
        User user = new User();
        BeanUtils.copyProperties(dto,user);
        user.setUpdateTime(LocalDateTime.now());
        user.setId(Integer.parseInt(String.valueOf(BaseContext.getCurrentId())));//转成Integer
        userMapper.update(user);
    }
}
